package com.fhnew.app.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.fhnew.app.R;
import com.fhnew.app.global.Constants;
import com.fhnew.app.model.internet.HttpAPI;
import com.fhnew.app.model.internet.HttpRequest;
import com.fhnew.app.model.internet.been.B_Login;
import com.fhnew.app.model.internet.been.B_RootList;
import com.fhnew.app.model.internet.model.UserModel;
import com.fhnew.app.ui.activity.main.MainActivity;
import com.fhnew.app.util.ActivityUtil;
import com.fhnew.app.util.HLog;
import com.fhnew.app.util.Md5;
import com.fhnew.app.util.VersionManager;
import com.fhnew.app.widget.LoadingDialog;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Administrator on 2017/8/4.
 * 启动页面
 * <p>
 * 如果用户已登录则直接登录否则获取根url地址保证网路正常 {@link SplashActivity#initS()}
 * 如果用户登录失败可能根地址失效，重新获取根地址 {postLogin#error()}
 */

public class SplashActivity extends
        AppCompatActivity
        implements EasyPermissions.PermissionCallbacks {

    //========================================================
    //View
    //========================================================

//    //    @Override
//    protected int setContentView () {
//        return R.layout.splash;
//    }


    private void GOHOME() {
        String[] ids = {Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE};
        requestPermission(this, "请同意以下权限以确保版本更新功能能够使用", 200, ids);
    }


    //========================================================
    //Control
    //========================================================
    private LoadingDialog dialog;
    private TextView tips;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ActivityUtil.fullScreen(this);
        super.onCreate(savedInstanceState);

        //初始化X5WebView
        X5WebActivity.initX5WebView(this);

        setContentView(R.layout.splash);

        dialog = new LoadingDialog((ViewGroup) findViewById(android.R.id.content).getRootView());
        dialog.setDialogCancelable(false);
        dialog.setShowTips(false);

        tips = findViewById(R.id.textView_SplashActivity_Tips);

        initS();
    }

    @Override
    protected void onDestroy() {
        getWindow().setBackgroundDrawable(null);//释放资源
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // EasyPermissions 权限处理请求结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //同意授权
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        hasPermission = true;
        enterHomeActivity();
    }

    //权限被拒
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Toast.makeText(this, "您拒绝了权限，将无法版本更新，如果需要版本更新功能，请到设置界面打开相应权限", Toast.LENGTH_LONG).show();
    }

    private HttpAPI.GetRootUrl getRootUrl = new HttpAPI.GetRootUrl() {

        @Override
        public void onStartedRequest(HttpRequest httpRequest) {
            super.onStartedRequest(httpRequest);
            dialog.showLoading();
            tips.setText("检查服务器地址...");
        }

        @Override
        public void result(B_RootList result) {

            if (result.getHosts() == null || result.getHosts().size() == 0) {
                Toast.makeText(SplashActivity.this, "当前无可用服务", Toast.LENGTH_SHORT).show();
            } else {


                Constants.adress = result.getHosts().get(0);
                userModel.setRootUrl(result.getHosts().get(0));
                hasHostUrl = true;

                HLog.I("服务器地址  ");

                if (userModel.isLogin()) {
                    HLog.I("启动页面登录" + userModel.getUserName() + "===" + userModel.getUserPassword());
                    postLogin.startRequest(userModel.getUserName(), Md5.toMd5(userModel.getUserPassword()));
                } else  {
                    dialog.dismiss();
                    enterHomeActivity();
                }
            }
        }

        @Override
        public void error(String msg) {
            dialog.dismiss();
            tips.setText("服务器地址获取失败");
            Toast.makeText(SplashActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
        }
    };

    private HttpAPI.PostLogin postLogin = new HttpAPI.PostLogin() {

        @Override
        public void onStartedRequest(HttpRequest httpRequest) {
            super.onStartedRequest(httpRequest);
            tips.setText("登录中...");
            dialog.showLoading();
        }

        @Override
        public void result(B_Login result) {
            userModel.login(result.getData());
            dialog.dismiss();
            hasHostUrl = true;

            enterHomeActivity();
        }

        @Override
        public void error(String msg) {
            dialog.dismiss();
            tips.setText("登录失败");
            userModel.loginOut();
            enterHomeActivity();
        }
    };

    //========================================================
    // Model
    //========================================================
    private boolean hasPermission = false;
    private boolean hasHostUrl = false;

    private UserModel userModel;

    /**
     * 获取屏幕信息
     */
    private void initS() {

        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);

        userModel = UserModel.getInstance(this);
        //修改位置
        getRootUrl.startRequest();

        GOHOME();

    }

    private void enterHomeActivity() {

        if (hasHostUrl && hasPermission) {

            VersionManager versionManager = new VersionManager();

            if (versionManager.versionCheck(this, 0, Constants.versionName)) {

                ProgressDialog progressDialog = new ProgressDialog(this);
                progressDialog.setTitle("下载更新");
                progressDialog.setMessage("新版本下载中...");
                progressDialog.setCancelable(false);
                progressDialog.setMax(100);
                progressDialog.show();

                HLog.I("下载地址" + Constants.versionurl);
                versionManager.downLoadAPP(SplashActivity.this, Constants.versionurl);
                versionManager.setDownLoadListener(new VersionManager.DownLoadListener() {
                    @Override
                    public void progress(float progress) {
                        progressDialog.setProgress((int) progress);
                    }

                    @Override
                    public void finish(String dir) {
                        if (dir == null) {
                            Toast.makeText(SplashActivity.this, "下载更新失败", Toast.LENGTH_SHORT).show();
                        } else {
                            VersionManager.installAPK(SplashActivity.this, dir);
                        }
                        progressDialog.hide();
                    }
                });
            } else {
                Intent intent = new Intent(this, MainActivity.class);
//              Intent intent = new Intent(this, TestActivity.class);
                startActivity(intent);
                finish();
            }

        }
    }

    /**
     * 请求权限
     *
     * @param context
     */
    public void requestPermission(Activity context, String tip, int requestCode, String[] perms) {
        EasyPermissions.requestPermissions(context, tip, requestCode, perms);
    }

}
